<template>
  <view class="page-container">
    <!-- 新增：Tab导航 -->
    <view class="tab-container">
      <scroll-view class="tab-scroll" scroll-x="true" :show-scrollbar="false">
        <view class="tab-nav">
          <view 
            class="tab-item" 
            :class="{ active: currentTab === 'pending' }"
            @click="switchTab('pending')"
          >
            <view class="tab-content">
              <text class="tab-text">待排课</text>
              <view class="tab-count" v-if="tabCounts.pending > 0">{{ tabCounts.pending }}</view>
            </view>
          </view>
          <view 
            class="tab-item" 
            :class="{ active: currentTab === 'confirming' }"
            @click="switchTab('confirming')"
          >
            <view class="tab-content">
              <text class="tab-text">待确认</text>
              <view class="tab-count" v-if="tabCounts.confirming > 0">{{ tabCounts.confirming }}</view>
            </view>
          </view>
          <view 
            class="tab-item" 
            :class="{ active: currentTab === 'completed' }"
            @click="switchTab('completed')"
          >
            <view class="tab-content">
              <text class="tab-text">已完成</text>
            </view>
          </view>
        </view>
      </scroll-view>
    </view>
    
    <!-- 筛选和排序（仅在待排课tab显示） -->
    <view v-if="currentTab === 'pending'">
      <DaDropdownVue2
        :dropdownMenu="dropdownMenuList"
        themeColor="#007aff"
        textColor="#333333"
        :duration="300"
        @confirm="handleConfirm"
        @close="handleClose"
        @open="handleOpen"
      >
        <template v-slot:slot1="{ item, index }">
          <view style="padding: 40px">自定义插槽内容</view>
        </template>
      </DaDropdownVue2>
    </view>

    <view class="card_list">
      <view class="card" v-for="(item, index) in filteredListData" :key="item.id">
        <view class="schedule-status" :class="getScheduleStatusClass(item.group_status, item.coach_id, item.pending_type, item.api_data)">
          {{ getScheduleStatus(item.group_status, item.pending_type, item.api_data) }}
        </view>
        <view class="invite-count" v-if="currentTab === 'confirming'">
          匹配中人数：{{ item.matching_count || 0 }} 人
        </view>
        <view class="goods-image">
          <view class="u-image">
            <image 
              :src="item.image || '/static/default-course.png'" 
              mode="aspectFill" 
              style="width: 100%; height: 312rpx;"
              @error="handleImageError"
            />
          </view>
        </view>
        <view class="card-content">
          <view class="title-price-row">
            <view class="title">{{ item.title }}</view>
            <view class="price-display">
              <!-- 一行展示：原价 + 新品价 + 标签 -->
              <view class="price-row">
                <!-- 价格部分 -->
                <view class="price-section">
                  <!-- 如果有新品价，显示原价（删除线）+ 新品价 -->
                  <template v-if="hasNewProductPrice(item)">
                    <text class="original-price">￥{{ getOriginalPrice(item) }}</text>
                    <text class="price-symbol">￥</text>
                    <text class="current-price">{{ getNewProductPrice(item) }}</text>
                  </template>
                  <!-- 否则只显示原价 -->
                  <template v-else>
                    <text class="price-symbol">￥</text>
                    <text class="current-price">{{ getOriginalPrice(item) }}</text>
                  </template>
                </view>
                
                <!-- 标签部分 -->
                <view class="price-tags-inline">
                  <text class="price-tag boutique-tag" v-if="item.group_status === 3">定制班</text>
                  <text 
                    class="price-tag new-product-tag" 
                    v-if="shouldShowNewProductTag(item)"
                  >
                    新品价
                  </text>
                </view>
              </view>
            </view>
          </view>
          <view class="info-row brief-intro">{{ item.brief_intro }}</view>
          <view class="info-row">
            <u-icon size="28" name="clock" color="#999999"></u-icon>
            <text>{{ item.start_time }}</text>
          </view>
          <view class="info-row">
            <u-icon size="28" name="map" color="#999999"></u-icon>
            <text>{{ item.address }}</text>
          </view>
          <view class="info-row">
            <u-icon size="28" name="calendar" color="#999999"></u-icon>
            <text>报名截止: {{ item.end_time }}</text>
          </view>

          <view v-if="item.matched_coach_name" class="matched-coach-info">
            <image 
              :src="item.matched_coach_avatar || '/static/default-avatar.png'" 
              mode="aspectFill" 
              class="coach-avatar"
              @error="handleImageError"
            />
            <view class="coach-details">
              <view class="coach-name">{{ item.matched_coach_name }}</view>
              <view class="coach-phone">{{ item.matched_coach_phone }}</view>
            </view>
          </view>

          <view class="action-buttons">
			  
			<!-- <view 
        class="action_btn star-btn" 
        :class="{ 'starred': item.api_data.is_star_top }" 
        @click="toggleStar(item)">
        <u-icon name="star" :color="item.api_data.is_star_top ? '#FFD700' : '#999999'" style="margin-right: 4px;"></u-icon>
        <text>星标</text>
      </view> -->
			  
            <view class="action_btn btn1" @click="checkDetail(item)">查看详情</view>
            
            <!-- 根据当前tab显示不同的操作按钮 -->
            <template v-if="currentTab === 'pending'">
              <!-- 待排课tab：显示邀请按钮 -->
              <view 
                class="action_btn btn2" 
                :class="[isInviteDisabled(item) ? 'disabled' : '']"
                v-if="shouldShowInviteButton(item)"
                @click="invite(item)"
              >
                邀请陪伴师
              </view>
            </template>
            
            <template v-else-if="currentTab === 'confirming'">
              <!-- 待确认tab：显示确认拒绝按钮或邀请陪伴师按钮 -->
              <template v-if="shouldShowConfirmButtons(item)">
                <view 
                  class="action_btn btn-confirm" 
                  :class="{ 'btn-loading': actionStates.confirming[item.id] }"
                  @click="confirmCoach(item)"
                >
                  <u-loading 
                    v-if="actionStates.confirming[item.id]" 
                    mode="circle" 
                    size="20" 
                    color="#fff"
                    style="margin-right: 8rpx;"
                  ></u-loading>
                  {{ actionStates.confirming[item.id] ? '确认中...' : '确认' }}
                </view>
                <view 
                  class="action_btn btn-reject" 
                  :class="{ 'btn-loading': actionStates.confirming[item.id] }"
                  @click="rejectCoach(item)"
                >
                  <u-loading 
                    v-if="actionStates.confirming[item.id]" 
                    mode="circle" 
                    size="20" 
                    color="#fff"
                    style="margin-right: 8rpx;"
                  ></u-loading>
                  {{ actionStates.confirming[item.id] ? '拒绝中...' : '拒绝' }}
                </view>
              </template>
              <template v-else>
                <!-- 系统指派待陪伴师确认或其他待确认状态：显示邀请陪伴师按钮 -->
                <view 
                  class="action_btn btn2" 
                  @click="invite(item)"
                >
                  邀请陪伴师
                </view>
              </template>
            </template>
            
            <template v-else-if="currentTab === 'completed'">
              <!-- 已完成tab：只显示查看详情，不显示其他操作按钮 -->
            </template>
          </view>
        </view>
      </view>
      <u-loadmore :status="status" :load-text="loadText" />
    </view>
  </view>
</template>
<script>
import DaDropdownVue2 from '@/components/da-dropdown-vue2/index.vue';
import { getCourseList, getCourseScheduleList, confirmGrab, getCourseScheduleDetail,setStarTop } from '@/api/class_share';
export default {
  components: {
    DaDropdownVue2,
  },
  // 配置页面
  onReady() {
    // #ifdef MP-WEIXIN
    wx.showShareMenu({
      withShareTicket: true,
      menus: ['shareAppMessage', 'shareTimeline']
    })
    // #endif
  },
  // 开启下拉刷新
  onShow() {
		this.getList(this.filterParams, true);
  },
  props: {
    content: {
      type: [Object, Array],
    },
    styles: {
      type: [Object, Array],
    },
  },
  data() {
    return {
      title: 'hello',
      listData: [],
      status: 'nomore',
      loadText: {
        loadmore: '轻轻上拉',
        loading: '努力加载中',
        nomore: '暂无更多数据',
      },
      listParams: {
        page: 1,
        size: 5,
      },
      filterParams: {},
      dropdownMenuList: [
        {
          title: '筛选',
          type: 'filter',
          prop: 'god4',
          options: [
            {
              title: '搜索课程',
              type: 'input',
              prop: 'course_name',
              placeholder: '请输入课程名称'
            },
            {
              title: '班级类型',
              type: 'checkbox',
              prop: 'class_type',
              options: [
                {
                  label: '体验班',
                  value: '1',
                },
                {
                  label: '标准班',
                  value: '2',
                },
                {
                  label: '周期班',
                  value: '3',
                },
                {
                  label: '定制周期班',
                  value: '4',
                },
              ],
            },
            {
              title: '课程类型',
              type: 'radio',
              prop: 'category',
              options: [
                {
                  label: '舞蹈',
                  value: '1',
                },
                {
                  label: '体育',
                  value: '2',
                },
                {
                  label: '音乐',
                  value: '3',
                },
              ],
            },
            {
              title: '时间',
              type: 'radio',
              prop: 'time_range',
              options: [
                {
                  label: '近三天',
                  value: '1',
                },
                {
                  label: '一周',
                  value: '2',
                },
                {
                  label: '一月',
                  value: '3',
                },
              ],
            },
            {
              title: '地区',
              type: 'radio',
              prop: 'district',
              options: [
                {
                  label: '海珠区',
                  value: '海珠区',
                },
                {
                  label: '天河区',
                  value: '天河区',
                },
                {
                  label: '越秀区',
                  value: '越秀区',
                },
                {
                  label: '荔湾区',
                  value: '荔湾区',
                },
                {
                  label: '白云区',
                  value: '白云区',
                },
                {
                  label: '黄埔区',
                  value: '黄埔区',
                },
                {
                  label: '番禺区',
                  value: '番禺区',
                },
                {
                  label: '花都区',
                  value: '花都区',
                },
                {
                  label: '南沙区',
                  value: '南沙区',
                },
                {
                  label: '从化区',
                  value: '从化区',
                },
                {
                  label: '增城区',
                  value: '增城区',
                },
              ],
            },
          ],
        },
        {
          title: '排序方式',
          type: 'cell',
          prop: 'sort',
          options: [
            {
              label: '按时间升序',
              value: { sort_by: 'start_time', order: 'asc' },
            },
            {
              label: '按时间降序',
              value: { sort_by: 'start_time', order: 'desc' },
            },
            {
              label: '按创建时间',
              value: { sort_by: 'created_at', order: 'desc' },
            },
            {
              label: '按价格低到高',
              value: { sort_by: 'price', order: 'asc' },
            },
            {
              label: '按价格高到低',
              value: { sort_by: 'price', order: 'desc' },
            },
            {
              label: '按匹配中人数',
              value: { sort_by: 'matching_count', order: 'desc' },
            },
          ],
        },
      ],
      currentTab: 'pending',
      tabCounts: {
        pending: 0,
        confirming: 0,
        completed: 0,
      },
      actionStates: {
        confirming: {},
      },
    };
  },
  computed: {
    filteredListData() {
      // 后端已经按tab分类并且排序了数据，前端直接使用
      return this.listData;
    }
  },
  methods: {
    checkDetail(item) {
      uni.navigateTo({
        url: `/pages/class_manage/detail?id=${item.id}`,
      });
    },
    getList(params, isNeedFresh) {
      if (isNeedFresh) {
        this.listParams.page = 1;
        this.listData = [];
        // 重置操作状态
        this.resetActionStates();
      }

      // 添加当前tab参数
      const requestParams = {
        ...params,
        ...this.listParams,
        tab: this.currentTab
      };

      return getCourseScheduleList(requestParams).then(res => {
        console.log('获取排课列表响应:', {
          tab: this.currentTab,
          params: requestParams,
          response: res,
          count: res?.list?.length,
          firstItem: res?.list?.[0]
        });
        
        if (res && res.list) {
          console.log('详细检查数据分类:', {
            tab: this.currentTab,
            items: res.list.map(item => ({
              schedule_id: item.schedule_id,
              title: item.course_title,
              group_status: item.group_status,
              coach_id: item.coach_id,
              pending_type: item.pending_type,
              matching_count: item.matching_count,
              matching_id: item.matching_id,
              matching_type: item.matching_type,
              matching_status: item.matching_status,
              // 添加状态判断结果
              computed_status: this.getScheduleStatus(item.group_status, item.pending_type, item),
              should_show_invite: this.shouldShowInviteButton({
                group_status: item.group_status,
                api_data: item
              }),
              should_show_confirm: this.shouldShowConfirmButtons({
                group_status: item.group_status,
                api_data: item
              })
            }))
          });
          
          console.log('图片处理调试:', {
            firstItemImage: res.list[0]?.image,
            ossDomain: this.$store.state.app.config.oss_domain,
            processedUrl: res.list[0] ? this.getImageUrl(res.list[0].image) : 'no item'
          });
          
          const formattedData = res.list.map(item => ({
            id: item.schedule_id,
            coach_id: item.coach_id,
            title: item.course_title,
            image: this.getImageUrl(item.image || item.cover_image),
            price: item.normal_price || item.price || '0.00',
            brief_intro: item.brief_intro,
            start_time: item.start_time,
            address: item.address,
            end_time: item.end_time,
            group_status: item.group_status,
            class_type: item.class_type,
            matching_count: item.matching_count || 0,
            pending_type: item.pending_type || 0,
            api_data: {
              ...item,
              matching_id: item.matching_id || null,
              matching_type: item.matching_type || null
            },
            matched_coach_name: item.coach_id > 0 ? item.coach_name : null,
            matched_coach_avatar: item.coach_id > 0 ? this.getImageUrl(item.coach_avatar) : null,
            matched_coach_phone: item.coach_id > 0 ? item.coach_phone : null
          }));
          
          console.log('格式化后的数据验证:', {
            tab: this.currentTab,
            count: formattedData.length,
            sample: formattedData[0],
            classification: formattedData.map(item => ({
              id: item.id,
              title: item.title,
              shouldShowInvite: this.shouldShowInviteButton(item),
              shouldShowConfirm: this.shouldShowConfirmButtons(item),
              status: this.getScheduleStatus(item.group_status, item.pending_type, item.api_data)
            }))
          });

          if (isNeedFresh) {
            this.listData = formattedData;
          } else {
            const existingIds = this.listData.map(item => item.id);
            const newData = formattedData.filter(item => !existingIds.includes(item.id));
            this.listData = [...this.listData, ...newData];
          }

          if (this.listData.length >= res.total || res.list.length < this.listParams.size) {
            this.status = 'nomore';
          } else {
            this.status = 'loadmore';
            this.listParams.page += 1;
          }

          this.listParams.total = res.total;
          
          // 更新tab计数
          this.updateTabCounts();
        } else {
          this.status = 'nomore';
          this.listData = [];
        }
      }).catch(err => {
        console.error('获取排课列表失败:', err);
        this.status = 'nomore';
        this.listData = [];
      });
    },
    updateTabCounts() {
      // 获取各tab的总数（需要单独调用接口获取数量）
      this.getTabCounts();
    },
    async getTabCounts() {
      try {
        // 并行获取各tab的数量
        const [pendingRes, confirmingRes, completedRes] = await Promise.all([
          getCourseScheduleList({ tab: 'pending', page: this.listParams.page, size: 1 }),
          getCourseScheduleList({ tab: 'confirming', page: this.listParams.page, size: 1 }),
          getCourseScheduleList({ tab: 'completed', page: this.listParams.page, size: 1 })
        ]);
        
        this.tabCounts.pending = pendingRes?.total || 0;
        this.tabCounts.confirming = confirmingRes?.total || 0;
        this.tabCounts.completed = completedRes?.total || 0;
      } catch (err) {
        console.error('获取tab计数失败:', err);
      }
    },
    switchTab(tab) {
      // 添加触觉反馈
      uni.vibrateShort({
        type: 'light'
      });
      
      this.currentTab = tab;
      
      // 切换tab时清空搜索条件
      if (tab !== 'pending') {
        this.filterParams = {};
      }
      
      // 重置操作状态
      this.resetActionStates();
      
      // 重新获取当前tab的数据
      this.getList({}, true);
    },
    loadmoreList() {
      if (this.status === 'nomore') return;
      
      this.status = 'loading';
      this.getList({ ...this.filterParams }, false);
    },
    handleConfirm(v) {
      console.log('handleConfirm ==>', v);
      this.filterParams = v;
      
      // 处理排序选项
      if (v.sort) {
        const sortOption = v.sort;
        // 将排序选项合并到过滤参数中
        this.filterParams = {
          ...this.filterParams,
          sort_by: sortOption.sort_by,
          order: sortOption.order
        };
      }
      
      this.getList(this.filterParams, true);
    },
    handleClose(v) {
      console.log('handleClose ==>', v);
    },
    handleOpen(v) {
      console.log('handleOpen ==>', v);
    },
    invite(item) {
      // 排课完成或失败时禁用邀请功能
      if (this.isScheduleFinished(item)) {
        uni.showToast({
          title: '该排课已完成或失败，无法邀请陪伴师',
          icon: 'none',
          duration: 2000
        });
        return;
      }
      
      uni.navigateTo({
        url: `/pages/teacher_manage/index?id=${item.id}`,
      });
    },
    getScheduleStatus(status, pendingType, apiData) {
      const groupStatus = parseInt(status);
      
      // 在已完成tab中，需要显示更具体的完成状态
      if (this.currentTab === 'completed') {
        if (groupStatus === 9) {
          return '已完成-排课失败';
        }
        if (groupStatus >= 1) {
          return '已完成-已排课';
        }
        
        // 🔥 新增：在已完成tab中显示过期状态
        if (groupStatus === 0) {
          const matchingId = apiData?.matching_id;
          const matchingStatus = apiData?.matching_status;
          
          if (matchingId && parseInt(matchingStatus) === 0 && this.isExpiredCourse({ start_time: apiData?.start_time })) {
            return '⏰ 已过期-待确认';
          }
          if (matchingId && parseInt(matchingStatus) === 2) {
            return '⏰ 已过期-被拒绝';
          }
          return '⏰ 已过期-未处理';
        }
      }
      
      // 1. 排课失败状态
      if (groupStatus === 9) {
        return '排课失败';
      }
      
      // 2. 已排课状态（group_status >= 1 且不是9）
      if (groupStatus >= 1) {
        return '已排课';
      }
      
      // 3. 排课流程中（group_status = 0）- 基于matching状态判断
      if (groupStatus === 0) {
        const matchingId = apiData?.matching_id;
        const matchingStatus = apiData?.matching_status;
        const matchingType = parseInt(apiData?.matching_type || 0);
        
        // 没有匹配记录，纯待排课状态
        if (!matchingId || matchingId === null) {
          return '待排课';
        }
        
        // 有匹配记录的情况
        if (matchingId) {
          // 被拒绝的匹配，回到待排课状态
          if (parseInt(matchingStatus) === 2) {
            return '待排课';
          }
          
          // 待处理的匹配
          if (parseInt(matchingStatus) === 0) {
            // 陪伴师抢单，需要管理员确认
            if (matchingType === 2) {
              return '待确认';
            }
            // 系统指派，等待陪伴师确认
            if (matchingType === 1) {
              return '待陪伴师确认';
            }
          }
          
          // 已确认的匹配
          if (parseInt(matchingStatus) === 1) {
            return '已确认待排课';
          }
        }
      }
      
      return '待排课';
    },
    getScheduleStatusClass(status, coachId, pendingType, apiData) {
      const numStatus = parseInt(status);
      
      // 在已完成tab中，使用特定的样式
      if (this.currentTab === 'completed') {
        if (numStatus === 9) {
          return 'completed-failed'; // 已完成-排课失败（红色）
        }
        if (numStatus >= 1) {
          return 'completed-success'; // 已完成-已排课（绿色）
        }
        
        // 🔥 新增：过期状态的专用样式类
        if (numStatus === 0) {
          const matchingId = apiData?.matching_id;
          const matchingStatus = apiData?.matching_status;
          
          if (matchingId && parseInt(matchingStatus) === 0 && this.isExpiredCourse({ start_time: apiData?.start_time })) {
            return 'expired-pending'; // 橙黄色 - 已过期-待确认
          }
          if (matchingId && parseInt(matchingStatus) === 2) {
            return 'expired-rejected'; // 深橙红色 - 已过期-被拒绝
          }
          if (this.isExpiredCourse({ start_time: apiData?.start_time })) {
            return 'expired-unprocessed'; // 金黄色 - 已过期-未处理
          }
        }
      }
      
      // 1. 排课失败状态
      if (numStatus === 9) {
        return 'schedule-failed'; // 红色
      }
      
      // 2. 已排课状态（group_status >= 1 且不是9）
      if (numStatus >= 1) {
        return 'scheduled-success'; // 绿色
      }
      
      // 3. 排课流程中（group_status = 0）- 基于matching状态判断
      if (numStatus === 0) {
        const matchingId = apiData?.matching_id;
        const matchingStatus = apiData?.matching_status;
        const matchingType = parseInt(apiData?.matching_type || 0);
        
        // 没有匹配记录，纯待排课状态
        if (!matchingId || matchingId === null) {
          return 'pending-schedule'; // 橙色
        }
        
        // 有匹配记录的情况
        if (matchingId) {
          // 被拒绝的匹配，回到待排课状态
          if (parseInt(matchingStatus) === 2) {
            return 'pending-schedule'; // 橙色
          }
          
          // 待处理的匹配
          if (parseInt(matchingStatus) === 0) {
            // 陪伴师抢单，需要管理员确认
            if (matchingType === 2) {
              return 'pending-confirm'; // 蓝色
            }
            // 系统指派，等待陪伴师确认
            if (matchingType === 1) {
              return 'system-assign-confirm'; // 蓝色
            }
          }
          
          // 已确认的匹配
          if (parseInt(matchingStatus) === 1) {
            return 'confirmed-pending'; // 浅绿色
          }
        }
      }
      
      return 'pending-schedule'; // 默认橙色
    },
    getCompletedStatusText(groupStatus) {
      const status = parseInt(groupStatus);
      
      const statusMap = {
        1: '已排课-周期班',
        2: '已排课-拼班中', 
        3: '已排课-定制班',
        4: '成班失败',
        5: '已取消',
        6: '已结算',
        7: '已分账',
        8: '已结束'
      };
      
      return statusMap[status] || '已完成';
    },
    refreshList() {
      this.getList({}, true);
    },
    // 确认陪伴师
    confirmCoach(item) {
      // 防止重复点击
      if (this.actionStates.confirming[item.id]) {
        return;
      }
      
      uni.showModal({
        title: '确认',
        content: '确定要接受该陪伴师吗？',
        success: (res) => {
          if (res.confirm) {
            this.handleCoachConfirmation(item, 'accept');
          }
        }
      });
    },
    
    // 拒绝陪伴师
    rejectCoach(item) {
      // 防止重复点击
      if (this.actionStates.confirming[item.id]) {
        return;
      }
      
      uni.showModal({
        title: '拒绝',
        content: '确定要拒绝该陪伴师吗？',
        success: (res) => {
          if (res.confirm) {
            this.handleCoachConfirmation(item, 'reject');
          }
        }
      });
    },
    
    // 处理确认/拒绝陪伴师
    handleCoachConfirmation(item, action) {
      console.log('处理确认/拒绝项目:', {
        action,
        item: {
          id: item.id,
          title: item.title,
          group_status: item.group_status,
          pending_type: item.pending_type,
          coach_id: item.coach_id,
          api_data: item.api_data
        }
      });

      // 设置确认状态
      this.$set(this.actionStates.confirming, item.id, true);
      
      // 添加触觉反馈
      uni.vibrateShort({
        type: action === 'accept' ? 'medium' : 'light'
      });

      // 从API数据中获取matching_id
      const matchingId = item.api_data?.matching_id;
      
      console.log('获取到的matching_id:', matchingId);

      if (matchingId && matchingId > 0) {
        this.confirmWithMatchingId(matchingId, action, item);
      } else {
        this.$set(this.actionStates.confirming, item.id, false);
        console.error('未找到有效的matching_id:', {
          matching_id: matchingId,
          api_data: item.api_data
        });
        uni.showToast({
          title: '未找到匹配ID，请刷新页面重试',
          icon: 'none',
          duration: 3000
        });
      }
    },
    
    // 使用matching_id进行确认/拒绝操作
    confirmWithMatchingId(matchingId, action, item) {
      confirmGrab({
        matching_id: matchingId,
        status: action === 'accept' ? 1 : 2 // 1表示接受，2表示拒绝
      }).then(res => {
        // 清除确认状态
        this.$set(this.actionStates.confirming, item.id, false);
        
        // 确认成功的处理逻辑
        console.log('确认操作成功响应:', res);
        
        // 使用固定的成功提示消息（因为request.js只返回data部分，无法获取msg）
        const successMsg = action === 'accept' ? '已接受陪伴师' : '已拒绝陪伴师';
        uni.showToast({
          title: successMsg,
          icon: 'success',
          duration: 2000
        });
        
        // 刷新列表数据
        this.getList(this.filterParams, true);
        
      }).catch(err => {
        // 清除确认状态
        this.$set(this.actionStates.confirming, item.id, false);
        
        // 显示错误提示
        console.error('确认/拒绝操作失败:', err);
        uni.showToast({
          title: typeof err === 'string' ? err : '操作失败，请重试',
          icon: 'none',
          duration: 2000
        });
      });
    },

    toggleStar(item) {
        item.api_data.is_star_top = !item.api_data.is_star_top;
        setStarTop({
          schedule_id: item.api_data.schedule_id,
          is_star_top: item.api_data.is_star_top
        }).then(res => {
          uni.showToast({
              title: item.api_data.is_star_top? '操作成功' : '已取消',
              icon: 'none'
            });
        }).catch(error => {
          console.error('API请求失败:', error);
          item.api_data.is_star_top = !item.api_data.is_star_top; // 恢复状态
          uni.showToast({
            title: '操作失败，请重试',
            icon: 'none'
          });
        });
    },
    
    // 价格相关方法 - 管理端专用逻辑
    getOriginalPrice(item) {
      return parseFloat(item.api_data?.normal_price || item.normal_price || item.price || 0).toFixed(2);
    },
    
    getNewProductPrice(item) {
      const priceInfo = item.api_data?.price_info || item.price_info;
      return parseFloat(priceInfo?.new_product_price || 0).toFixed(2);
    },
    
    hasNewProductPrice(item) {
      // 定制班不支持新品价
      if (item.group_status === 3 || item.class_type === 4) {
        return false;
      }
      const priceInfo = item.api_data?.price_info || item.price_info;
      return priceInfo && priceInfo.new_product_price_enabled && parseFloat(priceInfo.new_product_price || 0) > 0;
    },
    
    hasNewProductDiscount(item) {
      return this.hasNewProductPrice(item);
    },
    
    shouldShowNewProductTag(item) {
      // 判断是否显示新品价标签（定制班除外）
      // group_status === 3 是定制班，class_type === 4 也是定制班
      if (item.group_status === 3 || item.class_type === 4) {
        return false;
      }
      return this.hasNewProductPrice(item);
    },
    
    // 检查是否应该显示邀请按钮
    shouldShowInviteButton(item) {
      // 只有在待排课状态下才显示邀请按钮
      if (item.group_status !== 0) {
        return false;
      }
      
      const matchingId = item.api_data?.matching_id;
      const matchingStatus = item.api_data?.matching_status;
      
      // 1. 没有匹配记录的纯待排课状态
      if (!matchingId || matchingId === null) {
        return true;
      }
      
      // 2. 被拒绝后回到待排课状态
      if (matchingId && parseInt(matchingStatus) === 2) {
        return true;
      }
      
      return false;
    },
    
    // 检查是否应该显示确认拒绝按钮
    shouldShowConfirmButtons(item) {
      // 只有在group_status=0且有匹配记录的情况下才可能显示
      if (item.group_status !== 0) {
        return false;
      }
      
      // 🔥 新增：检查课程是否已过期
      if (this.isExpiredCourse(item)) {
        return false;
      }
      
      const matchingId = item.api_data?.matching_id;
      const matchingStatus = item.api_data?.matching_status;
      const matchingType = parseInt(item.api_data?.matching_type || 0);
      
      // 只有在陪伴师抢单且待处理状态时才显示确认拒绝按钮
      if (matchingId && 
          parseInt(matchingStatus) === 0 && 
          matchingType === 2) {
        return true;
      }
      
      return false;
    },
    
    // 检查排课是否已完成或失败
    isScheduleFinished(item) {
      const status = parseInt(item.group_status);
      return status !== 0;
    },
    
    // 检查邀请按钮是否应该禁用
    isInviteDisabled(item) {
      if (this.isScheduleFinished(item)) {
        return true;
      }
      return false;
    },
    
    // 重置操作状态
    resetActionStates() {
      this.actionStates = {
        confirming: {},
      };
    },
    
    // 图片加载错误处理
    handleImageError(e) {
      console.error('图片加载失败:', e);
      // 可以设置默认图片或其他处理逻辑
    },
    
    // 处理图片URL
    getImageUrl(url) {
      if (!url) return '/static/default-course.png';
      if (url.startsWith('http://') || url.startsWith('https://')) {
        return url;
      }
      
      // 首先尝试使用store中的oss_domain
      const ossDomain = this.$store.state.app.config.oss_domain;
      if (ossDomain) {
        return ossDomain + url;
      }
      
      // 如果store中没有oss_domain，使用固定域名作为备选
      return `https://txjmk-test.oss-cn-shenzhen.aliyuncs.com/${url}`;
    },
    
    // 🔥 新增：判断课程是否已过期
    isExpiredCourse(item) {
      if (!item.start_time) {
        return false;
      }
      
      const currentTime = new Date().getTime();
      const startTime = new Date(item.start_time).getTime();
      // 课程开始时间前1小时为报名截止时间
      const deadlineTime = startTime - (1 * 60 * 60 * 1000);
      
      return currentTime > deadlineTime;
    },
    fetchData() {
      this.getList({}, true);
    },
  },
  onLoad() {
    // 确保配置已加载
    if (!this.$store.state.app.config.oss_domain) {
      this.$store.dispatch('getConfig').then(() => {
        console.log('排课列表页配置已加载:', this.$store.state.app.config.oss_domain);
        this.fetchData();
      });
    } else {
      this.fetchData();
    }
  },
  onReachBottom() {
    this.loadmoreList();
  },
  onPullDownRefresh() {
    this.getList({}, true).then(() => {
      uni.stopPullDownRefresh();
    });
  },
};
</script>

<style lang="scss" scoped>
.page-container {
  background-color: #ffffff;
  min-height: 100vh;
  height: 100%;
  width: 100%;
  box-sizing: border-box;
  
  /* #ifdef MP-WEIXIN */
  height: 100vh;
  overflow: hidden;
  /* #endif */
}

.tab-container {
  display: flex;
  justify-content: center;
  padding: 24rpx;
  background-color: #ffffff;
  border-bottom: 1px solid #e1e1e1;

  .tab-scroll {
    width: 100%;
    white-space: nowrap;
    
    // 确保滚动条样式
    &::-webkit-scrollbar {
      display: none;
    }
  }

  .tab-nav {
    display: flex;
    gap: 32rpx;
    padding: 0 24rpx;
    justify-content: center;
    min-width: 100%;
    
    // 当tab数量较少时，确保等宽分布
    @media screen and (max-width: 500rpx) {
      gap: 16rpx;
      padding: 0 12rpx;
    }

    .tab-item {
      flex: 1;
      min-width: 180rpx;
      max-width: 240rpx;
      padding: 20rpx 32rpx;
      border-radius: 50rpx;
      font-size: 30rpx;
      font-weight: 600;
      color: #666;
      background-color: #f8f9fa;
      transition: all 0.3s ease;
      cursor: pointer;
      text-align: center;
      box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.05);
      position: relative;
      overflow: hidden;

      // 添加底部指示器
      &::after {
        content: '';
        position: absolute;
        bottom: 0;
        left: 50%;
        width: 0;
        height: 4rpx;
        background: linear-gradient(90deg, #0dc160, #13ce66);
        border-radius: 2rpx;
        transform: translateX(-50%);
        transition: width 0.3s ease;
      }

      &:active {
        transform: scale(0.98);
      }

      &.active {
        background: linear-gradient(135deg, #0dc160, #13ce66);
        color: #ffffff;
        box-shadow: 0 4rpx 16rpx rgba(13, 193, 96, 0.3);
        transform: translateY(-2rpx);
        
        &::after {
          width: 60rpx;
        }
      }

      .tab-content {
        display: flex;
        flex-direction: row;
        align-items: center;
        justify-content: center;
        white-space: nowrap;

        .tab-text {
          display: block;
          font-size: 30rpx;
          line-height: 1.2;
        }

        .tab-count {
          display: inline-block;
          min-width: 32rpx;
          height: 32rpx;
          line-height: 32rpx;
          padding: 0 8rpx;
          font-size: 20rpx;
          font-weight: bold;
          color: #ffffff;
          background-color: #ff4d4f;
          border-radius: 16rpx;
          text-align: center;
          margin-left: 8rpx;
          transform: scale(0.9);
        }
      }
      
      &.active .tab-content .tab-count {
        background-color: rgba(255, 255, 255, 0.9);
        color: #0dc160;
      }
    }
  }
}

.card_list {
  /* #ifdef MP-WEIXIN */
  padding-top: 180rpx; /* 搜索框+下拉菜单的高度 */
  height: calc(100vh - 180rpx);
  overflow-y: auto;
  /* #endif */
  
  /* #ifdef APP-PLUS */
  min-height: calc(100vh - 180rpx);
  overflow: auto;
  /* #endif */
}

.card {
  position: relative;
  margin: 32rpx 24rpx;
  background: #ffffff;
  border-radius: 20rpx;
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.08);
  overflow: hidden;
  display: flex;
  flex-direction: column;

  .schedule-status {
    position: absolute;
    top: 0;
    left: 0;
    padding: 8rpx 16rpx;
    font-size: 24rpx;
    font-weight: bold;
    color: #fff;
    background-color: #666;
    border-radius: 20rpx 0 16rpx 0; /* Match top-left border radius */
    z-index: 1;

    // 待排课状态
    &.pending-schedule {
      background-color: #f36806; // 橙色
    }
    
    // 待确认状态  
    &.pending-confirm {
      background-color: #007aff; // 蓝色
    }
    
    // 系统指派待确认状态
    &.system-assign-confirm {
      background-color: #007aff; // 蓝色
    }
    
    // 已确认待排课状态
    &.confirmed-pending {
      background-color: #52c41a; // 浅绿色
    }
    
    // 已排课成功
    &.scheduled-success {
      background-color: #0dc160; // 绿色
    }
    
    // 排课失败状态
    &.schedule-failed {
      background-color: #fa3534; // 红色
    }
    
    // 已完成状态
    &.scheduled-completed {
      background-color: #909399; // 灰色
    }
    
    // 已完成tab特定样式
    &.completed-success {
      background-color: #52c41a; // 深绿色 - 已完成-已排课
    }
    
    &.completed-failed {
      background-color: #ff4d4f; // 深红色 - 已完成-排课失败
    }
    
    // 🔥 新增：过期状态专用样式 - 统一灰色设计
    &.expired-pending,
    &.expired-rejected,
    &.expired-unprocessed {
      background: linear-gradient(135deg, #595959, #8c8c8c); // 统一灰色渐变 - 所有过期状态
      border: 2rpx solid #fff;
      box-shadow: 0 2rpx 8rpx rgba(89, 89, 89, 0.4);
    }
    
    // 兼容旧状态类（保留以防有其他地方使用）
    &.assign-pending {
      background-color: #f36806;
    }
    &.match-pending {
      background-color: #ff9900;
    }
    &.grouped {
      background-color: #0dc160;
    }
    &.failed {
      background-color: #fa3534;
    }
    &.completed {
      background-color: #909399;
    }
    &.unknown {
      background-color: #999999;
    }
  }
  .invite-count {
    position: absolute;
    top: 0;
    right: 0;
    padding: 8rpx 16rpx;
    font-size: 24rpx;
    font-weight: bold;
    color: #fff;
    background-color: rgba(0, 0, 0, 0.4); /* Slightly transparent background */
    border-radius: 0 20rpx 0 16rpx; /* Match top-right border radius */
    z-index: 1;
  }

  .goods-image {
    width: 100%;
    height: 312rpx;
    overflow: hidden;
    
    .u-image {
      width: 100%;
      height: 100%;
      
      image {
        width: 100%;
        height: 100%;
        object-fit: cover;
      }
    }
  }

  .card-content {
    padding: 24rpx;
    display: flex;
    flex-direction: column;
    flex-grow: 1; // Allow content to take remaining space

    .title-price-row {
      display: flex;
      justify-content: space-between;
      align-items: flex-start; // Align title and price at the top
      margin-bottom: 16rpx;

      .title {
        font-weight: 560;
        font-size: 32rpx;
        color: #010101;
        flex: 1; // Allow title to take available space
        margin-right: 16rpx; // Space between title and price
        line-height: 1.4; // Adjust line height if title wraps
      }

      .price-display {
        display: flex;
        flex-direction: column;
        align-items: flex-end;
        min-width: 200rpx;
        
        .price-row {
          display: flex;
          align-items: center;
          justify-content: flex-end;
          gap: 12rpx;
          flex-wrap: wrap;
          
          .price-section {
            display: flex;
            align-items: baseline;
            gap: 4rpx;
            white-space: nowrap;
            
            .original-price {
              font-size: 20rpx;
              color: #ccc;
              text-decoration: line-through;
              margin-right: 8rpx;
            }
            
            .price-symbol {
              font-size: 24rpx;
              color: #0dc160;
              font-weight: 500;
            }
            
            .current-price {
              font-size: 44rpx;
              color: #0dc160;
              font-weight: bold;
            }
          }
          
          .price-tags-inline {
            display: flex;
            align-items: center;
            gap: 6rpx;
            flex-wrap: wrap;
            
            .price-tag {
              padding: 4rpx 12rpx;
              border-radius: 12rpx;
              font-size: 20rpx;
              font-weight: 600;
              text-align: center;
              box-shadow: 0 2rpx 6rpx rgba(0, 0, 0, 0.15);
              white-space: nowrap;
              
              // 精品班标签
              &.boutique-tag {
                background: linear-gradient(135deg, #722ed1, #9254de);
                color: #fff;
                box-shadow: 0 2rpx 8rpx rgba(114, 46, 209, 0.3);
              }
              
              // 新人价标签
              &.newbie-tag {
                background: linear-gradient(135deg, #ff6b35, #ff8c42);
                color: #fff;
                box-shadow: 0 2rpx 8rpx rgba(255, 107, 53, 0.3);
              }
              
              // 新品价标签
              &.new-product-tag {
                background: linear-gradient(135deg, #52c41a, #73d13d);
                color: #fff;
                box-shadow: 0 2rpx 8rpx rgba(82, 196, 26, 0.3);
              }
              
              // 权益价标签
              &.benefit-tag {
                background: linear-gradient(135deg, #52c41a, #73d13d);
                color: #fff;
                box-shadow: 0 2rpx 8rpx rgba(82, 196, 26, 0.3);
              }
            }
          }
        }
      }
    }

    .info-row {
      display: flex;
      align-items: center;
      font-size: 24rpx;
      color: #666666; // Slightly darker grey for better readability
      line-height: 1.5;
      margin-top: 12rpx; // Consistent margin for info rows

      .u-icon {
        margin-right: 8rpx;
      }

      text {
        flex: 1; // Allow text to take available space
      }

      &.brief-intro {
        color: #999999; // Lighter grey for brief intro
        display: -webkit-box;
        -webkit-line-clamp: 2; // Limit to 2 lines
        -webkit-box-orient: vertical;
        overflow: hidden;
        text-overflow: ellipsis;
        margin-bottom: 16rpx; // Add some space below intro
      }
    }

    .matched-coach-info {
      display: flex;
      align-items: center;
      padding: 16rpx; // Reduced padding
      background-color: #f7f7f7;
      border-radius: 8rpx;
      margin-top: 24rpx; // Increased top margin
      margin-bottom: 24rpx; // Add bottom margin

      .coach-avatar {
        width: 60rpx; // Smaller avatar
        height: 60rpx;
        border-radius: 50%;
        margin-right: 16rpx;
        background-color: #eee; // Placeholder background
        flex-shrink: 0; // Prevent avatar from shrinking
      }

      .coach-details {
        flex: 1; // Allow details to take space
        min-width: 0; // Prevent overflow issues in flex container

        .coach-name {
          font-size: 28rpx;
          font-weight: bold;
          color: #333;
          white-space: nowrap;
          overflow: hidden;
          text-overflow: ellipsis;
        }

        .coach-phone {
          font-size: 24rpx;
          color: #666;
          white-space: nowrap;
          overflow: hidden;
          text-overflow: ellipsis;
        }
      }
    }

    .action-buttons {
      display: flex;
      justify-content: flex-end;
      margin-top: auto; // Push buttons to the bottom
      padding-top: 24rpx; // Add space above buttons
      flex-wrap: wrap; // 允许按钮换行

      .star-btn {
        padding: 10rpx 20rpx;
        display: flex;
        align-items: center;
        justify-content: center;
        border-radius: 8rpx;
        background-color: #f5f5f5;
        transition: all 0.3s;
        
        &.starred {
          background-color: #FFF8DC;
        }
      }

      .action_btn {
        min-width: 160rpx; // 设置最小宽度
        height: 70rpx;
        border-radius: 35rpx;
        text-align: center;
        line-height: 70rpx;
        font-weight: 500;
        font-size: 28rpx; // Smaller font size
        margin-left: 12rpx;
        margin-bottom: 12rpx; // 添加底部边距
        position: relative;
        overflow: hidden;
        transition: all 0.3s ease;
        display: flex;
        align-items: center;
        justify-content: center;

        // 按钮点击反馈
        &:active:not(.disabled):not(.btn-loading) {
          transform: scale(0.98);
        }

        // 加载状态
        &.btn-loading {
          opacity: 0.8;
          pointer-events: none;
          
          &::before {
            content: '';
            position: absolute;
            top: 0;
            left: -100%;
            width: 100%;
            height: 100%;
            background: linear-gradient(
              90deg,
              transparent,
              rgba(255, 255, 255, 0.2),
              transparent
            );
            animation: shimmer 1.5s infinite;
          }
        }

        &.btn1 {
          background: #fff;
          color: #333; // Darker text for better contrast
          border: 1px solid #e1e1e1;
          
          &:hover {
            background: #f8f9fa;
            border-color: #ddd;
          }
        }

        &.btn2 {
          background: linear-gradient(135deg, #0dc160, #13ce66);
          color: #ffffff;
          box-shadow: 0 2rpx 8rpx rgba(13, 193, 96, 0.3);
          
          &:hover:not(.disabled):not(.btn-loading) {
            background: linear-gradient(135deg, #0bb154, #11b95a);
            box-shadow: 0 4rpx 12rpx rgba(13, 193, 96, 0.4);
          }
        }
        
        &.btn-confirm {
          background: linear-gradient(135deg, #007aff, #409eff);
          color: #ffffff;
          box-shadow: 0 2rpx 8rpx rgba(0, 122, 255, 0.3);
          
          &:hover:not(.disabled):not(.btn-loading) {
            background: linear-gradient(135deg, #0056b3, #357abd);
            box-shadow: 0 4rpx 12rpx rgba(0, 122, 255, 0.4);
          }
        }
        
        &.btn-reject {
          background: linear-gradient(135deg, #fa3534, #ff6b6b);
          color: #ffffff;
          box-shadow: 0 2rpx 8rpx rgba(250, 53, 52, 0.3);
          
          &:hover:not(.disabled):not(.btn-loading) {
            background: linear-gradient(135deg, #d32f2f, #f44336);
            box-shadow: 0 4rpx 12rpx rgba(250, 53, 52, 0.4);
          }
        }
        
        &.disabled {
          background: #f5f5f5;
          color: #cccccc;
          border: 1px solid #e1e1e1;
          pointer-events: none;
          opacity: 0.6;
        }
        
        &.status-info {
          background: linear-gradient(135deg, #4CAF50, #66BB6A);
          color: #ffffff;
          box-shadow: 0 2rpx 8rpx rgba(76, 175, 80, 0.3);
          pointer-events: none;
        }
        
        &.btn-info {
          background: linear-gradient(135deg, #4CAF50, #66BB6A);
          color: #ffffff;
          box-shadow: 0 2rpx 8rpx rgba(76, 175, 80, 0.3);
          pointer-events: none;
        }
        
        &.btn-warning {
          background: linear-gradient(135deg, #FF9800, #FFB74D);
          color: #ffffff;
          box-shadow: 0 2rpx 8rpx rgba(255, 152, 0, 0.3);
        }
      }
    }
  }
}

// 加载动画
@keyframes shimmer {
  0% {
    left: -100%;
  }
  100% {
    left: 100%;
  }
}

.ljbm {
  color: #fff;
  border-radius: 4rpx;
  border: 1px solid transparent;
}

.experience-class {
  width: 88rpx;
  height: 32rpx;
  background: #f36806;
  border-radius: 4rpx;
  font-weight: 400;
  font-size: 22rpx;
  color: #ffffff;
  text-align: center;
  margin-left: 12rpx;
  margin-top: 8rpx;
}

.time {
  height: 24rpx;
  font-weight: 400;
  font-size: 24rpx;
  color: #999999;
  line-height: 24rpx;
  text-align: left;
  font-style: normal;
  margin-top: 32rpx;
}

.area {
  height: 24rpx;
  font-weight: 400;
  font-size: 24rpx;
  color: #999999;
  line-height: 24rpx;
  text-align: left;
  font-style: normal;
  margin-top: 16rpx;
  margin-bottom: 24rpx;
}

.number {
  width: 654rpx;
  height: 64rpx;
  border-radius: 8rpx;
  text-align: left;
  line-height: 64rpx;
}

.enrollment {
  width: 654rpx;
  height: 64rpx;
  border-radius: 8rpx;
  margin-top: 16rpx;
  text-align: left;
  line-height: 64rpx;
  color: #1e9956;
}
</style>
<!-- <template>
	<view>class_manage</view>
</template> -->


